<template>
  <div class="divBox relative">
    <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: 0 }">
      <div class="padding-add">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
          <el-form-item label="调货原因" prop="transferReason">
            <el-input
              v-model="queryParams.transferReason"
              placeholder="请输入调货原因"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="调货时间" prop="transferTime">
            <el-date-picker
              clearable
              v-model="queryParams.transferTime"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择调货时间"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item label="调货门店id" prop="transferRoomId">
            <!-- <el-input
              v-model="queryParams.transferRoomId"
              placeholder="请输入调货门店id"
              clearable
              @keyup.enter.native="handleQuery"
            /> -->
            <el-select
              v-model="queryParams.transferRoomId"
              placeholder="请选择调货门店"
              clearable
              @change="handleQuery"
            >
              <el-option v-for="item in roomList" :key="item.id" :label="item.roomName" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品id" prop="productId">
            <el-input
              v-model="queryParams.productId"
              placeholder="请输入商品id"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="商品规格id" prop="productSpecsId">
            <el-input
              v-model="queryParams.productSpecsId"
              placeholder="请输入商品规格id"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <!-- <el-form-item label="1:门店2:仓库" prop="transferMainBody">
            <el-select v-model="queryParams.transferMainBody">
              <el-option label="门店" value="1" />
              <el-option label="仓库" value="2" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="box-card mt14" :body-style="{ padding: '20px 20px' }" shadow="never" :bordered="false">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['stockroom:transfer:add']"
            >新增</el-button
          >
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['stockroom:transfer:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['stockroom:transfer:remove']"
            >删除</el-button
          >
        </el-col> -->
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['stockroom:transfer:export']"
            >导出</el-button
          >
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="saleroomList" @selection-change="handleSelectionChange" class="mt20">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="调货记录表id" align="center" prop="id" /> -->
        <!-- <el-table-column label="1:出库2:入库" align="center" prop="transferType" /> -->
        <el-table-column label="调货原因" align="center" prop="transferReason" />
        <el-table-column label="调货时间" align="center" prop="transferTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.transferTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="调货门店id" align="center" prop="transferRoomId" /> -->
        <el-table-column label="调货门店名称" align="center" prop="transferRoomName" />
        <!-- <el-table-column label="商品id" align="center" prop="productId" /> -->
        <el-table-column label="商品名称" align="center" prop="productName">
          <template slot-scope="scope">
            <span v-if="scope.row.transferInfoRequestList && scope.row.transferInfoRequestList.length > 0">{{
              scope.row.transferInfoRequestList.map((item) => item.productName).join('/')
            }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="商品规格id" align="center" prop="productSpecsId" /> -->
        <el-table-column label="商品规格" align="center" prop="productSpecs">
          <template slot-scope="scope">
            <span v-if="scope.row.transferInfoRequestList && scope.row.transferInfoRequestList.length > 0">{{
              scope.row.transferInfoRequestList.map((item) => item.productAttrValue).join('/')
            }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="调货数量" align="center" prop="transferNumber">
          <template slot-scope="scope">
            <span v-if="scope.row.transferInfoRequestList && scope.row.transferInfoRequestList.length > 0">{{
              scope.row.transferInfoRequestList.map((item) => item.transferNumber).join('/')
            }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="调货状态" align="center" prop="transferStatus">
          <template slot-scope="scope">
            <span>{{ scope.row.isSure === 1 ? '已确认' : '未确认' }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="1:门店2:仓库" align="center" prop="transferMainBody" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['stockroom:transfer:edit']"
              v-if="scope.row.isSure === 0"
              >修改</el-button
            >
            <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['stockroom:transfer:remove']"
              >删除</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改调货详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body class="transfer-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="transfer-form">
        <div class="basic-info">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="调货原因" prop="transferReason">
                <el-input v-model="form.transferReason" placeholder="请输入调货原因" :disabled="!!form.id" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="调货时间" prop="transferTime">
                <el-date-picker
                  clearable
                  v-model="form.transferTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择调货时间"
                  :disabled="!!form.id"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="调货中心" prop="transferRoomId">
                <el-select
                  v-model="form.transferRoomId"
                  placeholder="请选择调货中心"
                  @change="handleGiveawayChangeRoomId"
                  :disabled="!!form.id"
                >
                  <el-option v-for="item in roomList" :key="item.id" :label="item.roomName" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="goods-list">
          <div class="goods-list-header">
            <span class="title">调货商品</span>
          </div>
          <div v-for="(item, index) in form.transferInfoRequestList" :key="index" class="goods-item">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item
                  label="商品"
                  :prop="'transferInfoRequestList.' + index + '.productId'"
                  :rules="[{ required: true, message: '请选择商品', trigger: 'change' }]"
                >
                  <el-select
                    v-model="item.productId"
                    placeholder="请选择商品"
                    @change="(val) => handleGiveawayChange(val, index)"
                    filterable
                    :disabled="!!form.id"
                  >
                    <el-option
                      v-for="product in productList"
                      :key="product.id"
                      :label="product.name"
                      :value="product.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="规格"
                  :prop="'transferInfoRequestList.' + index + '.productSpecsId'"
                  :rules="[{ required: true, message: '请选择规格', trigger: 'change' }]"
                >
                  <el-select
                    v-model="item.productSpecsId"
                    placeholder="请选择规格"
                    :disabled="!item.productId || !!form.id"
                    @change="handleGiveawayChangeSpecsId(item.productSpecsId, index, item)"
                  >
                    <el-option v-for="spec in giveawayParams[index]" :key="spec.id" :label="spec.sku" :value="spec.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="数量"
                  :prop="'transferInfoRequestList.' + index + '.transferNumber'"
                  :rules="[
                    { required: true, message: '请输入数量', trigger: 'blur' },
                    { type: 'number', message: '必须为数字', trigger: 'blur' },
                    { type: 'number', min: 1, message: '必须大于0', trigger: 'blur' },
                  ]"
                >
                  <el-input-number
                    v-model.number="item.transferNumber"
                    :min="1"
                    placeholder="请输入数量"
                    controls-position="right"
                    style="width: 100%"
                  >
                  </el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="goods-item-actions">
              <el-button
                type="text"
                icon="el-icon-plus"
                @click="addFormItem"
                v-if="index === form.transferInfoRequestList.length - 1 && !form.id"
              >
                添加商品
              </el-button>
              <el-button
                type="text"
                icon="el-icon-delete" 
                @click="() => handleDelete(index)"
                v-if="form.transferInfoRequestList.length > 1 && !form.id"
                class="delete-btn"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSaleroom, getSaleroom, delSaleroom, addSaleroom, updateSaleroom } from '@/api/commercial';
import { productLstApi, productDetailApi } from '@/api/product';
import { listRoom } from '@/api/room';

export default {
  name: 'Commercial',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 调货详情表格数据
      saleroomList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        transferReason: null,
        transferTime: null,
        transferRoomId: null,
        productId: null,
        productSpecsId: null,
        transferMainBody: null,
        isSure: null,
      },
      // 表单参数
      form: {
        id: null,
        transferType: null,
        transferReason: null,
        transferTime: null,
        transferRoomId: null,
        transferMainBody: null,
        transferInfoRequestList: [{ productId: '', productSpecsId: '', transferNumber: '' }],
      },
      // 商品规格参数列表
      giveawayParams: {},
      // 商品列表
      productList: [],
      // 搜索关键词
      keywords: '',
      // 调货中心列表
      transferRoomList: [],
      // 表单校验
      rules: {
        transferReason: [
          { required: true, message: '请输入调货原因', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
        ],
        transferTime: [{ required: true, message: '请选择调货时间', trigger: 'change' }],
        transferRoomId: [{ required: true, message: '请选择调货中心', trigger: 'change' }],
        transferInfoRequestList: [
          { type: 'array', required: true, message: '请至少添加一条调货信息', trigger: 'change' },
        ],
      },
      roomList: [],
    };
  },
  created() {
    this.getList();
    this.gettransferRoomList();
  },
  methods: {
    handleGiveawayChangeRoomId(val) {
      this.form.transferRoomName = this.roomList.find((item) => item.id === val).roomName;
    },
    handleGiveawayChangeSpecsId(productId, index, item) {
      let list = this.giveawayParams[index].find((item) => item.id === productId);
      this.form.transferInfoRequestList[index].productAttrValue = list.sku;
    },
    /** 查询门店信息主列表 */
    gettransferRoomList() {
      this.loading = true;
      listRoom({ pageNum: 1, pageSize: 100 }).then((response) => {
        this.roomList = response.list;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 商品选择变化
    handleGiveawayChange(id, index) {
      if (!id) {
        this.$set(this.giveawayParams, index, []);
        this.form.transferInfoRequestList[index].productSpecsId = '';
        return;
      }
      this.loading = true;
      productDetailApi(id)
        .then((res) => {
          if (res.attrValueList && Array.isArray(res.attrValueList)) {
            this.$set(this.giveawayParams, index, res.attrValueList);
          } else {
            this.$set(this.giveawayParams, index, []);
            this.$message.warning('该商品暂无规格参数');
          }
          this.form.transferInfoRequestList[index].productSpecsId = '';
        })
        .catch((err) => {
          this.$set(this.giveawayParams, index, []);
          this.form.transferInfoRequestList[index].productSpecsId = '';
          this.$message.error(err.message || '获取商品规格失败');
        })
        .finally(() => {
          this.loading = false;
          this.form.transferInfoRequestList[index].productName = this.productList.find((item) => item.id === id).name;
        });
    },
    // 添加调货项
    addFormItem() {
      this.form.transferInfoRequestList.push({
        productId: '',
        productSpecsId: '',
        transferNumber: undefined,
      });
      this.$set(this.giveawayParams, this.form.transferInfoRequestList.length - 1, []);
    },
    // 删除调货项
    handleDelete(index) {
      this.form.transferInfoRequestList.splice(index, 1);
      // 重新整理规格参数数据
      const newGiveawayParams = {};
      this.form.transferInfoRequestList.forEach((item, idx) => {
        newGiveawayParams[idx] = this.giveawayParams[idx] || [];
      });
      this.giveawayParams = newGiveawayParams;
    },
    // 获取商品列表
    getProductList() {
      const params = {
        page: 1,
        limit: 999,
        type: 1,
        keywords: this.keywords ? encodeURIComponent(this.keywords) : '',
      };
      productLstApi(params)
        .then((res) => {
          this.productList = res.list || [];
        })
        .catch((err) => {
          this.$message.error(err.message || '获取商品列表失败');
        });
    },
    // 获取调货中心列表
    // getTransferRoomList() {
    //   // TODO: 实现获取调货中心列表的API调用
    //   this.transferRoomList = [
    //     { id: 1, name: '中心仓库' },
    //     { id: 2, name: '门店A' },
    //     { id: 3, name: '门店B' }
    //   ];
    // },
    /** 查询调货详情列表 */
    getList() {
      this.loading = true;
      listSaleroom(this.queryParams)
        .then((response) => {
          this.saleroomList = response.list;
          this.total = response.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        transferType: null,
        transferReason: null,
        transferTime: null,
        transferRoomId: null,
        transferMainBody: null,
        transferInfoRequestList: [
          {
            productId: '',
            productSpecsId: '',
            transferNumber: '',
          },
        ],
      };
      this.giveawayParams = { 0: [] };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加调货详情';
      this.getProductList();
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      const response = await getSaleroom(id);
      await this.getProductList(); // 确保商品下拉已加载
      this.form = response;
      this.open = true;
      this.title = '修改调货详情';
      this.gettransferRoomList();
      // 为每个已选商品获取规格下拉
      if (this.form.transferInfoRequestList && this.form.transferInfoRequestList.length > 0) {
        await Promise.all(
          this.form.transferInfoRequestList.map(async (item, idx) => {
            if (item.productId) {
              const res = await productDetailApi(item.productId);
              this.$set(this.giveawayParams, idx, res.attrValueList || []);
            } else {
              this.$set(this.giveawayParams, idx, []);
            }
          }),
        );
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateSaleroom(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addSaleroom(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'saleroom/saleroom/export',
        {
          ...this.queryParams,
        },
        `saleroom_${new Date().getTime()}.xlsx`,
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.divBox {
  .padding-add {
    padding: 20px;
  }
  .mt14 {
    margin-top: 14px;
  }
  .mt20 {
    margin-top: 20px;
  }
  .mb8 {
    margin-bottom: 8px;
  }
}

.transfer-dialog {
  .transfer-form {
    padding: 0 20px;

    .basic-info {
      margin-bottom: 30px;
      padding-bottom: 20px;
      border-bottom: 1px solid #ebeef5;
    }

    .goods-list {
      .goods-list-header {
        margin-bottom: 20px;
        .title {
          font-size: 16px;
          font-weight: 500;
          color: #303133;
          position: relative;
          padding-left: 12px;
          &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 16px;
            background-color: #409eff;
            border-radius: 2px;
          }
        }
      }

      .goods-item {
        padding: 20px;
        margin-bottom: 20px;
        background-color: #f8f9fb;
        border-radius: 4px;

        &:last-child {
          margin-bottom: 0;
        }

        .goods-item-actions {
          text-align: right;
          margin-top: 10px;

          .delete-btn {
            color: #f56c6c;
            margin-left: 10px;
            &:hover {
              color: #ff4d4f;
            }
          }
        }
      }
    }
  }

  .el-form-item {
    margin-bottom: 20px;
  }

  .el-select {
    width: 100%;
  }

  .el-date-picker {
    width: 100%;
  }

  .dialog-footer {
    padding: 20px;
    text-align: right;
    border-top: 1px solid #ebeef5;
  }
}
</style>
